package com.hd.crdao.activity;

import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.adapter.MyGpsLocationDetailAdapter;
import com.hd.crdao.base.BaseSecondActivity;
import com.hd.crdao.bean.GpsDetailBean;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.DensityUtil;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.CustomScrollView;
import com.hd.crdao.view.ExpandHeadView;
import com.hd.crdao.wrapper.GpsDrawable;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;

/**
 * @author Administrator
 * @date 2017/12/6
 */

public class GpsLocationDetailsActivity extends BaseSecondActivity implements CustomScrollView.OnScrollListener {
    @BindView(R.id.gpslocationdetails)
    ExpandHeadView mGpsLocationDetails;
    @BindView(R.id.aboveArea)
    LinearLayout mAboveArea;
    /* @BindView(R.id.driveTrack)
     TextView mDriveTrack;*/
    @BindView(R.id.anomalyStatistics)
    TextView mAnomalyStatistics;
    @BindView(R.id.header_item)
    LinearLayout mHeaderPart;
    @BindView(R.id.customScrollView)
    CustomScrollView mCustomScrollView;
    @BindView(R.id.gpsrecyclerview)
    RecyclerView mGpsrecyclerview;
    public int mFromTopHigh;
    @BindView(R.id.replacelayout)
    LinearLayout mReplaceLayout;
    @BindView(R.id.goToplayout)
    LinearLayout mGoTopLayout;
    @BindView(R.id.bdMapview)
    MapView mMapView;
    public Handler mHandler = new Handler();
    @BindView(R.id.statusMessage)
    TextView mStatusMessage;
    @BindView(R.id.gdSpeed)
    TextView mGdSpeed;
    @BindView(R.id.tranPlate)
    TextView mTranPlate;
    @BindView(R.id.veFrame)
    TextView mVeFrame;
    @BindView(R.id.gdDevid)
    TextView mGdDevid;
    @BindView(R.id.gdCuradd)
    TextView mGdCuradd;
    @BindView(R.id.gdLsttime)
    TextView mGdLsttime;

    private ArrayList<Marker> mMarkers = new ArrayList<>();

    public MyGpsLocationDetailAdapter mMyGpsLocationDetailAdapter;
    public int mMeasuredHeight;
    public BaiduMap mBaiduMap;


    @Override
    protected int setContentView() {
        return R.layout.activity_gpslocationdetails;
    }

    @Override
    protected ExpandHeadView setExpandHeadView() {
        return mGpsLocationDetails;
    }


    @Override
    protected void initView() {
        initData();
        initListener();
    }

    /**
     * 对所有的控件进行初始化数据
     */
    private void initData() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mGpsrecyclerview.setLayoutManager(linearLayoutManager);
        int displayWidth = DensityUtil.getDisplayWidth(UIUtils.getContext());
        int height = displayWidth * 3 / 4;
        mMapView.setLayoutParams(new LinearLayout.LayoutParams(displayWidth, height));
        mBaiduMap = mMapView.getMap();
        loadData();


    }

    private void loadData() {
        String vehicleTblId = getIntent().getStringExtra("vehicleTblId") + "";
        // String vehicleTblId = "0b1eaa8178e64542b9274e423c2a2775";
        OkHttpUtils.post().url(Constants.GETVEHICLETBLGPSINFO_URL).addParams("vehicleTblId", vehicleTblId).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("网络开了个小差");
            }

            @Override
            public void onResponse(String response, int id) {
                GpsDetailBean gpsDetailBean = new Gson().fromJson(response, GpsDetailBean.class);
                if (gpsDetailBean.getSuccess() == 0) {
                    mStatusMessage.setText(gpsDetailBean.getGpsDevice().getStatusMessage());
                    String gdSpeed = gpsDetailBean.getGpsDevice().getGdSpeed();
                    if (!TextUtils.isEmpty(gdSpeed)) {
                        mGdSpeed.setText(gdSpeed + "km/s");
                    } else {
                        mGdSpeed.setText("0km/s");
                    }

                    mTranPlate.setText(gpsDetailBean.getGpsDevice().getVehicleTbl().getTranPlate());
                    mVeFrame.setText(gpsDetailBean.getGpsDevice().getVehicleTbl().getVeFrame());
                    mGdDevid.setText(gpsDetailBean.getGpsDevice().getGdDevid());
                    mGdCuradd.setText(gpsDetailBean.getGpsDevice().getGdCuradd());
                    mGdLsttime.setText(gpsDetailBean.getGpsDevice().getGdLsttime());
                    mAnomalyStatistics.setText((mAnomalyStatistics.getText().toString()) + "(" + String.valueOf(gpsDetailBean.getGpsEventTotal()) + ")");
                    List<GpsDetailBean.ListGpsEventBean> listGpsEvent = gpsDetailBean.getListGpsEvent();
                    initDataForRecyclerView(listGpsEvent);
                    initDataForMapView(gpsDetailBean);
                } else {
                    MyToast.show(gpsDetailBean.getMessage());
                }
            }
        });
    }

    private void initListener() {
        mCustomScrollView.setOnScrollListener(this);
    }


    /**
     * 此处应该访问接口获得数据
     *
     * @param listGpsEvent
     */
    private void initDataForRecyclerView(List<GpsDetailBean.ListGpsEventBean> listGpsEvent) {

        mMyGpsLocationDetailAdapter = new MyGpsLocationDetailAdapter(listGpsEvent);
        mGpsrecyclerview.setAdapter(mMyGpsLocationDetailAdapter);
        /*mMyGpsLocationDetailAdapter.setOnItemClickLister(new MyGpsLocationDetailAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                MyToast.show("当前位置是" + position);
            }
        });*/
    }

    /**
     * 给百度地图进行数据初始化
     */
    private void initDataForMapView(GpsDetailBean gpsDetailBean) {
        if (gpsDetailBean != null) {
            String gdOricoord = gpsDetailBean.getGpsDevice().getGdOricoord();
            LatLng center = Parse2Lat(gdOricoord);
            initLocation(mBaiduMap, center);
            List<GpsDetailBean.ListGpsRecordBean> listGpsRecord = gpsDetailBean.getListGpsRecord();
            ArrayList<LatLng> latLngs = new ArrayList<>();
            latLngs.add(0, center);
            for (int i = 0; i < listGpsRecord.size(); i++) {
                LatLng latLng = Parse2Lat(listGpsRecord.get(i).getGrCoord());
                latLngs.add(latLng);
            }
            ArrayList<String> list = new ArrayList<>();
            for (int i = 0; i < gpsDetailBean.getListGpsEvent().size(); i++) {
                GpsDetailBean.ListGpsEventBean gpsEventBean = gpsDetailBean.getListGpsEvent().get(i);
                if (gpsEventBean.getGrCoord() != null) {
                    list.add((gpsEventBean.getGrCoord() + "," + gpsEventBean.getGeEvent()));
                } else {
                    list.add(String.valueOf(gpsEventBean.getGeEvent()));
                }
            }
            addMultiMarker(latLngs, center, gpsDetailBean.getGpsDevice().getGdElefence(), list);

        }
    }


    /**
     * 对地图进行初始化
     *
     * @param mBaiduMap
     * @param center
     */
    private void initLocation(BaiduMap mBaiduMap, LatLng center) {
        mBaiduMap.setMyLocationEnabled(true);
        MapStatus mapStatus = new MapStatus.Builder().zoom(16.0f).target(center).build();
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(mapStatus));

    }

    /**
     * 在地图上添加一些标记
     *
     * @param mLatLngList 各个坐标的集合
     * @param center      设置中心点的坐标
     * @param radius      设置围栏半径
     * @param list        所有异常点集合
     */
    private void addMultiMarker(List<LatLng> mLatLngList, LatLng center, int radius, ArrayList<String> list) {
        //设置地图的圆心
        OverlayOptions ooCircle = new CircleOptions().fillColor(0x6699FFFF)
                .center(center).stroke(new Stroke(3, 0x6633CCFF))
                .radius(radius);
        mBaiduMap.addOverlay(ooCircle);

        //绘制折线
        if (mLatLngList.size() >= 2) {
            OverlayOptions ooPolyline = new PolylineOptions().width(10)
                    .color(0xAA00FF00).points(mLatLngList);
            mBaiduMap.addOverlay(ooPolyline);
        }

        //绘制起始点坐标
        MarkerOptions origin = new MarkerOptions().position(center)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.origin))
                .zIndex(7).animateType(MarkerOptions.MarkerAnimateType.grow);
        mBaiduMap.addOverlay(origin);

        //添加各个异常标记点
        for (int i = 0; i < list.size(); i++) {
            String content = list.get(i);
            if (content.contains(",")) {
                String[] split = content.split(",");
                LatLng latLng = new LatLng(Double.parseDouble(split[0]), Double.parseDouble(split[1]));
                BitmapDescriptor bitmapDescriptor = getBitmapDescriptor((i + 1), Integer.parseInt(split[2]));
                MarkerOptions markerOptions = new MarkerOptions().position(latLng).icon(bitmapDescriptor)
                        .zIndex(7).animateType(MarkerOptions.MarkerAnimateType.grow);
                Marker marker = (Marker) mBaiduMap.addOverlay(markerOptions);
                mMarkers.add(marker);
            }
        }

        //给各个异常点设置点击事件
        ALog.d("添加标记完成");
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                int postion = -1;
                for (int i = 0; i < mMarkers.size(); i++) {
                    if (mMarkers.get(i) == marker) {
                        postion = i;
                        break;
                    }
                }
                if (postion >= 0) {
                    ALog.d("执行marker点击" + postion);
                    scrollToPosition(postion);
                }
                return true;
            }
        });
    }

    /**
     * @param position  根据当前的位置设置当前是第几个marker
     * @param eventFlag 根据eventFlag 显示不同图标
     * @return
     */
    private BitmapDescriptor getBitmapDescriptor(int position, int eventFlag) {
        View view = View.inflate(UIUtils.getContext(), R.layout.bitmapview, null);
        TextView mCustomView = (TextView) view.findViewById(R.id.bitmapview);
        int gpsDrawable = GpsDrawable.getGpsDrawable(eventFlag);
        mCustomView.setBackgroundResource(gpsDrawable);
        mCustomView.setText("" + position);
        //  mCustomView.setTextSize(UIUtils.dip2Px(10));
        return BitmapDescriptorFactory.fromView(view);

    }

    /**
     * 改变粘性头的状态
     *
     * @param state
     */
    public void changeHeaderState(boolean state) {
        /*if (state) {
            mDriveTrack.setBackgroundColor(UIUtils.getColor(R.color.colorAppMain));
            mDriveTrack.setTextColor(UIUtils.getColor(R.color.white));

            mAnomalyStatistics.setTextColor(UIUtils.getColor(R.color.colorAppMain));
            mAnomalyStatistics.setBackgroundColor(UIUtils.getColor(R.color.white));
        } else {
            mDriveTrack.setTextColor(UIUtils.getColor(R.color.colorAppMain));
            mDriveTrack.setBackgroundColor(UIUtils.getColor(R.color.white));

            mAnomalyStatistics.setBackgroundResource(R.color.colorAppMain);
            mAnomalyStatistics.setTextColor(UIUtils.getColor(R.color.white));

        }*/

    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus) {
            //获取searchLayout的顶部位置
            mFromTopHigh = mAboveArea.getBottom();
            ALog.d("" + mFromTopHigh);
            mMeasuredHeight = mGpsrecyclerview.getMeasuredHeight();
        }
        super.onWindowFocusChanged(hasFocus);
    }

    @Override
    public void onScroll(int scrollY) {
        //  ALog.d("a里面滑动？");
        if (scrollY >= mFromTopHigh + UIUtils.dip2Px(50)) {
            if (mHeaderPart.getParent() != mReplaceLayout) {
                mGoTopLayout.removeView(mHeaderPart);
                mReplaceLayout.addView(mHeaderPart);
                //  changeHeaderState(false);
                //  mGpsLocationDetails.setVisibility(View.GONE );
            }
        } else {
            if (mHeaderPart.getParent() != mGoTopLayout) {
                mReplaceLayout.removeView(mHeaderPart);
                mGoTopLayout.animate();
                mGoTopLayout.addView(mHeaderPart);
                //changeHeaderState(true);
                // mGpsLocationDetails.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 拦截scrollview对mapview滑动事件的干扰
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_MOVE) {
            mMapView.requestDisallowInterceptTouchEvent(true);
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * scrollview滑动到指定位置
     *
     * @param position
     */
    public void scrollToPosition(final int position) {
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                mCustomScrollView.smoothScrollTo(0, (
                        UIUtils.dip2Px(50) + mFromTopHigh + mMeasuredHeight / mMyGpsLocationDetailAdapter.getItemCount())
                        * (position + 1) - mHeaderPart.getMeasuredHeight());
            }
        });
    }


    @Override
    protected void onDestroy() {
        if (mBaiduMap != null) {
            mBaiduMap.clear();
            mBaiduMap = null;
        }
        if (mMapView != null) {
            mMapView.onDestroy();
            mMapView = null;
        }
        super.onDestroy();
    }

    /**
     * 将经纬度格式的字符串转换成经纬度
     *
     * @param location
     * @return
     */
    public LatLng Parse2Lat(String location) {
        if (location != null && !TextUtils.isEmpty(location)) {
            String[] split = location.split(",");
            return new LatLng(Double.parseDouble(split[0]), Double.parseDouble(split[1]));
        }
        return null;
    }
}

